/*
 * Copyright 2025 The JA-SIG Collaborative. All rights reserved.
 * distributed with this file and available online at
 */
package com.lap.auth.adapter.driving.persistence.header.repository;

import com.lap.auth.adapter.driving.persistence.header.HeaderCache;
import com.lap.auth.adapter.driving.persistence.header.HeaderConverter;
import com.lap.auth.adapter.driving.persistence.header.mapper.HeaderMapper;
import com.lap.auth.adapter.driving.persistence.header.po.HeaderPo;
import com.lap.auth.domain.header.Header;
import com.lap.auth.domain.header.repository.HeaderRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;

@RequiredArgsConstructor
@Repository
public class HeaderRepositoryImpl implements HeaderRepository {

  private final HeaderConverter headerConverter;
  private final HeaderMapper headerMapper;

  @CacheEvict(value = HeaderCache.HEADER, key = "#header.userId+':'+#header.code")
  @Override
  public void save(Header header) {
    HeaderPo headerPo = headerConverter.toPo(header);
    var query = headerMapper.selectByPrimaryKey(header.getUserId(), header.getCode());
    if (query == null) {
      headerMapper.insert(headerPo);
    } else {
      headerMapper.updateByPrimaryKey(headerPo);
    }
  }

  @Cacheable(value = HeaderCache.HEADER, key = "#userId +':'+#code", unless = "#result == null")
  @Override
  public Header findByUserIdAndCode(Integer userId, String code) {
    return headerConverter.toDomain(headerMapper.selectByPrimaryKey(userId, code));
  }
}
